package com.pusilkom.uploader;

/**
 * @author Purwa
 * @version Draft
 * @Name ListenerAutoDebetWorker
 * @Desc Listen the socket request from webserver ( PHP ).
 */

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.pusilkom.logger.Debuger;
import com.pusilkom.logger.FileLoger;

public class ListenerAutodebetWorker implements Runnable{
	
	private ServerSocket server;
	private int serverPort;
	protected ExecutorService threadPool = Executors.newFixedThreadPool(5);
	private FileLoger flog;
	private AutodebetWorkerConfig conf;
	private Debuger agent;
	
	public ListenerAutodebetWorker(int port, AutodebetWorkerConfig config, Debuger debug) {
		this.serverPort = port;
		this.conf = config;		
		this.agent = debug;
	}

	/**
	 * Run the server socket listener
	 */
	@Override
	public void run() {
		flog = new FileLoger("AutodebetWorker",conf.getParameter("logPath"));
		this.activateListener();
		while(true) {
			try {
				Socket connected = this.server.accept();
				agent.debug("Client connected . . .");
				this.threadPool.execute(new ListenerAutodebetWorkerThread(connected, conf, flog));
			} catch (IOException e) {
				flog.writeException(e, "Socket error / tidak tersambung");
			}			
		}
	}
	
	private void activateListener() {
		try {
			server = new ServerSocket(this.serverPort);
			agent.debug("Socket server started at port "+this.serverPort);
		} catch (IOException e) {
			flog.writeException(e, "Tidak bisa membuka port : "+this.serverPort);
		}
	}
}
